package main.java.com.leng.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leng.dao.BookMapper;
import com.leng.dao.CorrelationMapper;
import com.leng.pojo.*;
import com.leng.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by presoul on 2017/6/13.
 */
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CorrelationMapper correlationMapper;

    @Override
    public EasyUIDataGridResult getAllbooks(Integer page, double rows) {
        BookExample example = new BookExample();
        PageHelper.startPage(page, (int) rows);
        List<Book> list = bookMapper.selectByExample(example);

        PageInfo<Book> pageInfo = new PageInfo<Book>(list);

        EasyUIDataGridResult result = new EasyUIDataGridResult();
        result.setTotal(pageInfo.getTotal());
        result.setRows(list);
        return result;
    }

    @Override
    public List<Correlation> getUserRent(Integer id) {

        CorrelationExample example = new CorrelationExample();
        CorrelationExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(id);

        List<Correlation> list = correlationMapper.selectByExample(example);

        return list;
    }

    @Override
    public List<Book> getAllUserRentBook(List<Correlation> list) {

        List<Book> list1 = new ArrayList<>();

        for (Correlation correlation : list) {
            list1.add(bookMapper.selectByPrimaryKey(correlation.getBookId()));
        }

        return list1;

    }

    @Override
    public void updateBookSum(Integer id, Integer userId) {

        Correlation correlation = new Correlation();
        correlation.setBookId(id);
        correlation.setUserId(userId);
        correlationMapper.insert(correlation);

        Book book = bookMapper.selectByPrimaryKey(id);
        book.setBookRenttime(new Date());
        book.setBookNumber(book.getBookNumber() - 1);

        if (book.getBookNumber() < 1) {
            book.setBookStatus(1);
        }

        bookMapper.updateByPrimaryKey(book);

    }

    @Override
    public EasyUIDataGridResult getAllQuerybooks(Integer page, double rows, String query) {
        BookExample example = new BookExample();
        BookExample.Criteria criteria = example.createCriteria();

        criteria.andBookNameLike("%"+query+"%");

        PageHelper.startPage(page, (int) rows);
        List<Book> list = bookMapper.selectByExample(example);

        PageInfo<Book> pageInfo = new PageInfo<Book>(list);

        EasyUIDataGridResult result = new EasyUIDataGridResult();
        result.setTotal(pageInfo.getTotal());
        result.setRows(list);
        return result;
    }


}
